package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.api.DownloadExample;
import com.amazon.shop.api.GetFeed;
import com.amazon.shop.api.UploadExample;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.*;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.spapi.api.FeedsApi;
import com.amazon.shop.spapi.client.ApiException;
import com.amazon.shop.spapi.model.feeds.*;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.utils.OssUtils;
import com.amazon.shop.utils.XMLUtils;
import com.amazon.shop.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-12
 */
@RestController
@RequestMapping("/shop/product")
@Api(tags = "产品模块")
public class ProductController {
    @Resource
    private AmazonAuthorityService amazonAuthorityService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductPicService productPicService;
    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private ProductVariantService productVariantService;
    @Resource
    private ProductSkuService productSkuService;
    @Resource
    private ProductLanguageInfoService productLanguageInfoService;
    @Resource
    private CountryService countryService;
    @Resource
    private AccountAuthorizationService accountAuthorizationService;
    @Resource
    private OssUtils ossUtils;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private UploadDataService uploadDataService;
    @Resource
    private MessageStatusService messageStatusService;

    /**
     * 更新产品信息
     *
     * @return
     */
    @SystemLog(value = "更新产品信息")
    @PostMapping("/updateProduct")
    @Transactional
    @ApiOperation(value = "更新产品信息")
    public CommonResult updateProduct(@RequestBody ProductVo productVo, @RequestParam(required = false) MultipartFile multipartFile) {
        String number = productVo.getNumbers();
        Product product = productService.getById(number);
        //对应属性对拷
        BeanUtils.copyProperties(productVo, product);
        System.out.println(product);

        ProductTypeVo productTypeVo = productVo.getProductTypeVo();
        //获取产品分类
        //获取产品一级分类
        String productTypeOne = productTypeVo.getProductTypeOne();
        //获取产品二级分类
        String productTypeTwo = productTypeVo.getProductTypeTwo();
        //获取产品三级分类
        String productTypeThree = productTypeVo.getProductTypeThree();
        //获取产品四级分类
        String productTypeFour = productTypeVo.getProductTypeFour();
        //获取产品五级分类
        String productTypeFive = productTypeVo.getProductTypeFive();
        //获取产品六级分类
        String productTypeSix = productTypeVo.getProductTypeSix();

        //处理产品分类数据 通过产品分类查询产品分类编号
        QueryWrapper<ProductType> productTypeQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(productTypeOne)) {
            productTypeQueryWrapper.and((wrapper) -> {
                wrapper.eq("product_type_one", productTypeOne);
                if (!StringUtils.isEmpty(productTypeTwo)) {
                    wrapper.eq("product_type_two", productTypeTwo);
                    if (!StringUtils.isEmpty(productTypeThree)) {
                        wrapper.eq("product_type_three", productTypeThree);
                        if (!StringUtils.isEmpty(productTypeFour)) {
                            wrapper.eq("product_type_four", productTypeFour);
                            if (!StringUtils.isEmpty(productTypeFive)) {
                                wrapper.eq("product_type_five", productTypeFive);
                                if (!StringUtils.isEmpty(productTypeSix)) {
                                    wrapper.eq("product_type_six", productTypeSix);
                                }
                            }
                        }
                    }
                }
            });
        }
        ProductType productType = productTypeService.getOne(productTypeQueryWrapper);
        String productTypeId = productType.getProductTypeId();
        //更新修改后的产品属性编号
        product.setProductTypeId(productTypeId);

        //更新产品翻译信息
        ProductLanguageInfoVo productLanguageInfoVo = productVo.getProductLanguageInfoVo();
        //根据产品编号查询对应翻译信息
        QueryWrapper<ProductLanguageInfo> productLanguageInfoQueryWrapper = new QueryWrapper<>();
        productLanguageInfoQueryWrapper.eq("product_id", number);
        ProductLanguageInfo one = productLanguageInfoService.getOne(productLanguageInfoQueryWrapper);
        String id = one.getId();
        ProductLanguageInfo productLanguageInfo = new ProductLanguageInfo();
        one.setProductId(id);
        BeanUtils.copyProperties(productLanguageInfoVo, productLanguageInfo);
        productLanguageInfoService.updateById(productLanguageInfo);

        //根据产品编号查询对应变体列表
        List<ProductVariantVo> variantMap = productVo.getVariantMap();
        List<ProductVariant> productVariants = variantMap.stream().map((variant) -> {
            ProductVariant productVariant = new ProductVariant();
            productVariant.setProductId(number);
            BeanUtils.copyProperties(variant, productVariant);
            return productVariant;
        }).collect(Collectors.toList());
        //批量更新产品变体信息
        productVariantService.updateBatchById(productVariants);

        //根据产品编号查询对应图片信息
        QueryWrapper<ProductPic> productPicQueryWrapper = new QueryWrapper<>();
        productPicQueryWrapper.eq("product_id", number);
        List<ProductPic> productPicList = productPicService.list(productPicQueryWrapper);
        List<ProductPicVo> images = productVo.getImages();
        List<ProductPic> productPics = images.stream().map((item) -> {
            ProductPic productPic = new ProductPic();
            BeanUtils.copyProperties(item, productPic);
            return productPic;
        }).collect(Collectors.toList());
        //本地上传图片
        String url = ossUtils.uploadOssLocalFile(number, multipartFile);
        ProductPic pic = new ProductPic();
        pic.setProductId(number);
        pic.setPath(url);
        BeanUtils.copyProperties(productPicList, productPics);
        productPics.add(pic);
        //批量保存图片信息
        productPicService.saveOrUpdateBatch(productPics);

        //保存更新的sku
        String sku = productVo.getSku();
        String skuId = product.getSkuId();
        ProductSku productSku = productSkuService.getById(skuId);
        productSku.setSku(sku);
        productSkuService.updateById(productSku);

        return CommonResult.success("更新产品信息成功").put("list", number);
    }


    /**
     * 删除产品
     *
     * @param productId
     * @return
     */
    @SystemLog(value = "删除产品信息")
    @Transactional
    @PostMapping("/deleteProduct")
    @ApiOperation(value = "删除产品信息")
    public CommonResult deleteProduct(String productId, String token) {
        boolean flag = permissionsService.getPermissionList(token, "13");
        if (flag) {
            //根据产品编号删除产品
            productService.removeById(productId);

            //根据产品编号删除产品图片
            UpdateWrapper<ProductPic> productPicUpdateWrapper = new UpdateWrapper<>();
            productPicUpdateWrapper.eq("product_id", productId);
            productPicService.remove(productPicUpdateWrapper);

            //根据产品编号删除产品sku
            UpdateWrapper<ProductSku> productSkuUpdateWrapper = new UpdateWrapper<>();
            productSkuUpdateWrapper.eq("product_id", productId);
            productSkuService.remove(productSkuUpdateWrapper);

            //根据产品编号删除产品变体
            UpdateWrapper<ProductVariant> productVariantUpdateWrapper = new UpdateWrapper<>();
            productVariantUpdateWrapper.eq("product_id", productId);
            productVariantService.remove(productVariantUpdateWrapper);

            //根据产品编号删除产品翻译信息
            UpdateWrapper<ProductLanguageInfo> productLanguageInfoUpdateWrapper = new UpdateWrapper<>();
            productLanguageInfoUpdateWrapper.eq("product_id", productId);
            productLanguageInfoService.remove(productLanguageInfoUpdateWrapper);

            String userRealName = usersService.getUserRealName(token);

            return CommonResult.success("删除产品信息成功")
                    .put("list", productId)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 接收采集到的产品信息
     *
     * @return
     */
    @SystemLog(value = "采集产品")
    @PostMapping("/saveProduct")
    @ApiOperation(value = "采集产品")
    @Transactional
    public CommonResult saveProduct(@RequestBody ProductSaveVo productSaveVo) {
        List<ProductPicVo> images = productSaveVo.getImages();

        Product product = new Product();
        String sku = productSaveVo.getSku();

        //生成随机产品编号
        String productNumber = UUID.randomUUID().toString().replace("-", "") + "product";
        if (!StringUtils.isEmpty(sku)) {
            ProductSku productSku = new ProductSku();
            productSku.setSku(sku);
            productSku.setProductId(productNumber);
            //设置自定义sku编号
            String skuNumber = productNumber.replace("product", "sku");
            productSku.setSkuId(skuNumber);
            //保存产品Sku
            productSkuService.save(productSku);
            //产品设置sku编号
            product.setSkuId(skuNumber);
        }

        for (ProductPicVo productPicVo : images) {
            //获取图片网络路径
            String picPath = productPicVo.getPicPath();
            if (!StringUtils.isEmpty(picPath)) {
                //上传图片网络流保存在Oss
                String url = ossUtils.uploadOssWebFile(productNumber, picPath);
                ProductPic productPic = new ProductPic();
                //上传成功后将图片地址保存到数据库
                BeanUtils.copyProperties(productPicVo, productPic);
                if (!StringUtils.isEmpty(sku)) {
                    productPic.setSku(sku);
                }
                productPic.setProductId(productNumber);
                //将oss路径设置为图片对应路径
                productPic.setPath(url);
                productPicService.save(productPic);
            }

            //保存产品分类
            ProductTypeVo productTypeVo = productSaveVo.getProductTypeVo();
            //根据产品分类查询产品分类编号
            QueryWrapper<ProductType> productTypeQueryWrapper = new QueryWrapper<>();
            String productTypeOne = productTypeVo.getProductTypeOne();
            String productTypeTwo = productTypeVo.getProductTypeTwo();
            String productTypeThree = productTypeVo.getProductTypeThree();
            String productTypeFour = productTypeVo.getProductTypeFour();
            String productTypeFive = productTypeVo.getProductTypeFive();
            String productTypeSix = productTypeVo.getProductTypeSix();
            if (!StringUtils.isEmpty(productTypeOne)) {
                productTypeQueryWrapper.and((wrapper) -> {
                    wrapper.eq("product_type_one", productTypeOne);
                    if (!StringUtils.isEmpty(productTypeTwo)) {
                        wrapper.eq("product_type_two", productTypeTwo);
                        if (!StringUtils.isEmpty(productTypeThree)) {
                            wrapper.eq("product_type_three", productTypeThree);
                            if (!StringUtils.isEmpty(productTypeFour)) {
                                wrapper.eq("product_type_four", productTypeFour);
                                if (!StringUtils.isEmpty(productTypeFive)) {
                                    wrapper.eq("product_type_five", productTypeFive);
                                    if (!StringUtils.isEmpty(productTypeSix)) {
                                        wrapper.eq("product_type_six", productTypeSix);
                                    }
                                }
                            }
                        }
                    }
                });
                //设置产品对应的分类号
                ProductType productType = productTypeService.getOne(productTypeQueryWrapper);
                if (productType != null) {
                    String productTypeId = productType.getProductTypeId();
                    product.setProductTypeId(productTypeId);
                }
            }
        }

        //保存产品变体
        List<ProductVariantVo> variantMap = productSaveVo.getVariantMap();
        List<ProductVariant> productVariantList = variantMap.stream().map((variant) -> {
            ProductVariant productVariant = new ProductVariant();
            productVariant.setProductId(productNumber);
            BeanUtils.copyProperties(variant, productVariant);
            return productVariant;
        }).collect(Collectors.toList());
        productVariantService.saveBatch(productVariantList);

        //保存产品翻译内容
        List<ProductLanguageInfoVo> productLanguageInfoVos = productSaveVo.getProductLanguageInfoVos();
        List<ProductLanguageInfo> productLanguageInfoList = productLanguageInfoVos.stream().map((productLanguageInfoVo) -> {
            ProductLanguageInfo productLanguageInfo = new ProductLanguageInfo();
            BeanUtils.copyProperties(productLanguageInfoVo, productLanguageInfo);

            //通过国家编号查询国家信息
            String countryId = productLanguageInfoVo.getCountryId();
            Country country = countryService.getById(countryId);
            String name = country.getName();
            //设置国家名称
            productLanguageInfo.setProductId(productNumber);
            productLanguageInfo.setCountry(name);

            return productLanguageInfo;
        }).collect(Collectors.toList());
        //批量保存产品翻译信息
        productLanguageInfoService.saveBatch(productLanguageInfoList);

        //对应属性对拷
        BeanUtils.copyProperties(productSaveVo, product);
        //设置状态为采集完成
        product.setCollectionStatus(0);
        //设置产品编号
        product.setNumbers(productNumber);
        //保存产品信息
        productService.save(product);
        return CommonResult.success("采集成功").put("list", productNumber);
    }

    /**
     * 采集列表
     *
     * @return
     */
    @GetMapping("/collectionList")
    @ApiOperation(value = "采集列表与产品列表")
    public CommonResult CollectionList(Integer i, String token) {

        boolean flag = permissionsService.getPermissionList(token, "22");

        if (flag) {

            //查询订单列表
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            if (i == 0) {
                productQueryWrapper.eq("collection_status", 0);
            } else {
                productQueryWrapper.eq("collection_status", 1);
            }

            List<Product> list = productService.list(productQueryWrapper);
            List<ProductSaveVo> productSaveVoList = list.stream()
                    .map(product -> {
                        ProductSaveVo productSaveVo = new ProductSaveVo();
                        if (!StringUtils.isEmpty(product)) {

                            BeanUtils.copyProperties(product, productSaveVo);

                            //查询产品类型
                            String productTypeId = product.getProductTypeId();
                            ProductType productType = productTypeService.getById(productTypeId);
                            ProductTypeVo productTypeVo = new ProductTypeVo();
                            if (!StringUtils.isEmpty(productType)) {
                                BeanUtils.copyProperties(productType, productTypeVo);
                                productSaveVo.setProductTypeVo(productTypeVo);
                            }

                            //查询产品图片
                            String productNumbers = product.getNumbers();
                            QueryWrapper<ProductPic> productPicQueryWrapper = new QueryWrapper<>();
                            productPicQueryWrapper.and(wrapper -> {
                                wrapper.eq("product_id", productNumbers);
                            });
                            ProductPicVo productPicVo = new ProductPicVo();
                            List<ProductPic> productPicList = productPicService.list(productPicQueryWrapper);
                            List<ProductPicVo> productPicVoList = productPicList.stream()
                                    .map(productPic -> {
                                        if (!StringUtils.isEmpty(productPic)) {
                                            BeanUtils.copyProperties(productPic, productPicVo);
                                        }
                                        return productPicVo;
                                    })
                                    .collect(Collectors.toList());
                            productSaveVo.setImages(productPicVoList);

                            //查询变体，根据产品id
                            QueryWrapper<ProductVariant> variantQueryWrapper = new QueryWrapper<>();
                            variantQueryWrapper.and(wrapper -> {
                                wrapper.eq("product_id", productNumbers);
                            });
                            ProductVariantVo productVariantVo = new ProductVariantVo();
                            List<ProductVariant> productVariantList = productVariantService.list(variantQueryWrapper);
                            List<ProductVariantVo> productVariantVoList = productVariantList.stream()
                                    .map(productVariant -> {
                                        if (!StringUtils.isEmpty(productVariant)) {
                                            BeanUtils.copyProperties(productVariant, productVariantVo);
                                        }
                                        return productVariantVo;
                                    }).collect(Collectors.toList());
                            productSaveVo.setVariantMap(productVariantVoList);

                            //查询操作日志
                            QueryWrapper<OperationLog> operationLogQueryWrapper = new QueryWrapper<>();
                            operationLogQueryWrapper.eq("table_id", productNumbers);
                            List<OperationLog> operationLogList = operationLogService.list(operationLogQueryWrapper);
                            if (operationLogList != null) {
                                List<OperationLogVo> operationLogVoList = operationLogList.stream().map((operationLog) -> {
                                    OperationLogVo operationLogVo = new OperationLogVo();
                                    BeanUtils.copyProperties(operationLog, operationLogVo);
                                    return operationLogVo;
                                }).collect(Collectors.toList());
                                productSaveVo.setLogs(operationLogVoList);
                            }

                            //查询sku，根据sku的id查询
                            String productSkuId = product.getSkuId();
                            ProductSku sku = productSkuService.getById(productSkuId);
                            if (!StringUtils.isEmpty(sku)) {
                                productSaveVo.setSku(sku.getSku());
                            }

                            //查询产品翻译信息
                            QueryWrapper<ProductLanguageInfo> infoQueryWrapper = new QueryWrapper<>();
                            infoQueryWrapper.eq("product_id", productNumbers);
                            List<ProductLanguageInfo> productLanguageInfoList = productLanguageInfoService.list(infoQueryWrapper);
                            ProductLanguageInfoVo productLanguageInfoVo = new ProductLanguageInfoVo();
                            List<ProductLanguageInfoVo> languageInfoVoList = productLanguageInfoList.stream()
                                    .map(productLanguageInfo -> {
                                        if (!StringUtils.isEmpty(productLanguageInfo)) {
                                            BeanUtils.copyProperties(productLanguageInfo, productLanguageInfoVo);
                                        }
                                        return productLanguageInfoVo;
                                    })
                                    .collect(Collectors.toList());
                            productSaveVo.setProductLanguageInfoVos(languageInfoVoList);

                        }
                        return productSaveVo;
                    })
                    .collect(Collectors.toList());

            String userRealName = usersService.getUserRealName(token);

            return CommonResult
                    .success("查询成功")
                    .put("productSaveVoList", productSaveVoList)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 查询产品图片
     *
     * @param token
     * @param productId
     * @param path
     * @return
     */
    @GetMapping("/selectPic")
    @ApiOperation(value = "产品图片")
    public CommonResult selectPic(String token, String productId, String path) {
        boolean flag = permissionsService.getPermissionList(token, "16");

        if (flag) {
            QueryWrapper<ProductPic> picQueryWrapper = new QueryWrapper<>();
            if (productId != null && path != null) {
                picQueryWrapper.and(wrapper -> {
                    wrapper.eq("product_id", productId);
                });
                picQueryWrapper.or(wrapper -> {
                    wrapper.eq("path", path);
                });
            } else if (productId != null && path == null) {
                picQueryWrapper.and(wrapper -> {
                    wrapper.eq("product_id", productId);
                });
            } else if (productId == null && path != null) {
                picQueryWrapper.and(wrapper -> {
                    wrapper.eq("path", path);
                });
            }
            picQueryWrapper.groupBy("product_id");
            List<ProductPic> productPicList = productPicService.list(picQueryWrapper);
            List<String> pathList = productPicList.stream()
                    .map(ProductPic::getPath)
                    .collect(Collectors.toList());

            String userRealName = usersService.getUserRealName(token);

            return CommonResult
                    .success("查询成功")
                    .put("pathList", pathList)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 查询所有变体
     *
     * @param variant
     * @param i       控制是否模糊搜索
     * @return
     */
    @PostMapping("/selectProductVariant")
    @ApiOperation(value = "查询所有变体")
    public CommonResult selectProductVariant(String token, @RequestParam(required = false) String variant, @RequestParam(required = false) Integer i) {
        boolean flag = permissionsService.getPermissionList(token, "10");

        if (flag) {
            QueryWrapper<ProductVariant> variantQueryWrapper = new QueryWrapper<>();
            if (variant != null && i != null) {
                variantQueryWrapper.and(wrapper -> {
                    wrapper.like("variant", variant);
                });
            } else if (variant != null && i == null) {
                variantQueryWrapper.and(wrapper -> {
                    wrapper.eq("variant", variant);
                });
            }
            List<ProductVariant> variantList = productVariantService.list(variantQueryWrapper);
            ProductVariantVo productVariantVo = new ProductVariantVo();
            List<ProductVariantVo> productVariantVoList = variantList.stream()
                    .map(productVariant -> {
                        BeanUtils.copyProperties(productVariant, productVariantVo);
                        return productVariantVo;
                    })
                    .collect(Collectors.toList());

            String userRealName = usersService.getUserRealName(token);

            return CommonResult
                    .success("查询成功")
                    .put("productVariantVoList", productVariantVoList)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE, ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 根据变体id删除变体
     *
     * @param variantId
     * @param token
     * @return
     */
    @SystemLog(value = "删除变体")
    @Transactional
    @PostMapping("/deleteProductVariant")
    @ApiOperation(value = "删除变体")
    public CommonResult deleteProductVariant(String variantId, String token) {
        boolean flag = permissionsService.getPermissionList(token, "13");
        if (flag) {
            ProductVariant productVariant = productVariantService.getById(variantId);
            if (!StringUtils.isEmpty(productVariant)) {
                boolean removeById = productVariantService.removeById(productVariant.getVariantId());
                if (removeById) {
                    String userRealName = usersService.getUserRealName(token);
                    return CommonResult.success("删除成功")
                            .put("list", variantId)
                            .put("salesman", userRealName);
                }
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 添加变体
     *
     * @param productVariantVo
     * @param token
     * @return
     */
    @SystemLog(value = "添加变体")
    @Transactional
    @PostMapping("/addProductVariant")
    @ApiOperation(value = "添加变体")
    public CommonResult addProductVariant(@RequestBody ProductVariantVo productVariantVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "13");

        if (flag) {
            ProductVariant productVariant = new ProductVariant();
            String variantId = UUID.randomUUID().toString().replace("-", "") + "variant";
            productVariant.setVariantId(variantId);
            if (!StringUtils.isEmpty(productVariantVo.getVariant())) {
                BeanUtils.copyProperties(productVariantVo, productVariant);
                boolean save = productVariantService.save(productVariant);
                if (save) {

                    String userRealName = usersService.getUserRealName(token);

                    return CommonResult.success("添加成功")
                            .put("list", variantId)
                            .put("salesman", userRealName);
                }
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 修改变体名称
     *
     * @param variant
     * @param newVariant
     * @param token
     * @return
     */
    @SystemLog(value = "修改变体名字")
    @Transactional
    @PostMapping("/updateProductVariant")
    @ApiOperation(value = "修改变体名字")
    public CommonResult updateProductVariant(String variant, String newVariant, String token) {
        boolean flag = permissionsService.getPermissionList(token, "13");
        if (flag) {
            QueryWrapper<ProductVariant> variantQueryWrapper = new QueryWrapper<>();
            variantQueryWrapper.eq("variant", variant);
            List<ProductVariant> productVariantList = productVariantService.list(variantQueryWrapper);
            productVariantList.stream()
                    .peek(productVariant -> {
                        productVariant.setVariant(newVariant);
                    })
                    .collect(Collectors.toList());
            List<String> variantId = productVariantList.stream()
                    .map(ProductVariant::getVariantId)
                    .collect(Collectors.toList());
            boolean updateBatchById = productVariantService.updateBatchById(productVariantList);
            if (updateBatchById) {
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("删除产品信息成功")
                        .put("list", variantId)
                        .put("salesman", userRealName);
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 上传产品
     *
     * @return
     */
    @SystemLog(value = "上传产品")
    @PostMapping("/uploadProduct")
    @ApiOperation(value = "上传产品")
//    @Transactional
    public CommonResult uploadProduct(@RequestBody List<ProductUploadVo> productVoList
            , String token, String id) throws ParserConfigurationException, TransformerException {
        boolean flag = permissionsService.getPermissionList(token, "26");
        if (flag) {
            //根据授权账户查询授权店铺信息
            AccountAuthorization authorization = accountAuthorizationService.getById(id);

            //根据授权站点编号查询授权信息
            String number = authorization.getNumber();
            AmazonAuthority amazonAuthority = amazonAuthorityService.getById(number);
            GetFeedResponse getFeedResponse = null;
            try {
                //获取销售人员姓名
                String userRealName = usersService.getUserRealName(token);
                int size = productVoList.size();

                getFeedResponse = uploadProductApi(amazonAuthority, productVoList, userRealName, size);
                List<String> collect = productVoList.stream().map(ProductUploadVo::getMessageId).collect(Collectors.toList());

                return CommonResult.success("上传成功")
                        .put("list", collect)
                        .put("salesman", userRealName)
                        .put("feedResponse", getFeedResponse);

            } catch (ApiException e) {
                System.out.println(e.getResponseHeaders());
                System.out.println(e.getResponseBody());
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取亚马逊产品api
     *
     * @param authority
     * @return
     */
    public GetFeedResponse uploadProductApi(AmazonAuthority authority
            , List<ProductUploadVo> productUploadVoList, String userName, int size) throws ParserConfigurationException, TransformerException, ApiException {
        //1.创建提要文档
        FeedsApi feedsExample = GetFeed.getFeedsExample(authority);
        CreateFeedDocumentSpecification createFeedDocumentSpecification = new CreateFeedDocumentSpecification();
        createFeedDocumentSpecification.setContentType("text/plain; charset=UTF-8");
        CreateFeedDocumentResponse feedDocument = feedsExample.createFeedDocument(createFeedDocumentSpecification);
        String feedDocumentId = feedDocument.getPayload().getFeedDocumentId();
        String key = feedDocument.getPayload().getEncryptionDetails().getKey();
        String initializationVector = feedDocument
                .getPayload()
                .getEncryptionDetails()
                .getInitializationVector();
        String url = feedDocument.getPayload().getUrl();

        //生成xml文件
        String xmlData = "";
        File xml = XMLUtils.createXML(productUploadVoList);
        try {
            FileInputStream fileInputStream = new FileInputStream(xml);
            byte[] xmlByte = new byte[fileInputStream.available()];
            fileInputStream.read(xmlByte);
            fileInputStream.close();
            String s = new String(xmlByte, "UTF-8");
            xmlData = s;
        } catch (IOException e) {
            e.printStackTrace();
        }

        //2.亚马逊上传api
        UploadExample uploadExample = new UploadExample();
        uploadExample.encryptAndUploadFromPipedInputStream(key, initializationVector, url, xmlData);

        //通过站点编号查询站点信息
        String id = authority.getId();
        AccountAuthorization authorization = accountAuthorizationService.getById(id);

        //通过站点账户查询站点国家
        QueryWrapper<AccountAuthorization> accountAuthorizationQueryWrapper = new QueryWrapper<>();
        String authorizationAccount = authorization.getAuthorizationAccount();
        accountAuthorizationQueryWrapper.eq("authorization_account", authorizationAccount);
        List<AccountAuthorization> authorizationList = accountAuthorizationService.list(accountAuthorizationQueryWrapper);
        List<AccountAuthorization> collect = authorizationList.stream().filter(auth -> "1".equals(auth.getBenchmarkAccount())).collect(Collectors.toList());

        //获取国家编号
        List<String> list = collect.stream().map(AccountAuthorization::getCountryId).collect(Collectors.toList());

        //根据国家编号查询国家列表
        List<Country> countryList = countryService.listByIds(list);

        //通过国家列表查询店铺列表
        List<String> marketplaceIds = countryList.stream().map(Country::getMarketplaceId).collect(Collectors.toList());

        CreateFeedSpecification createFeedSpecification = new CreateFeedSpecification();
        createFeedSpecification.setFeedType("POST_PRODUCT_DATA");
        createFeedSpecification.setMarketplaceIds(marketplaceIds);
        createFeedSpecification.setInputFeedDocumentId(feedDocumentId);

        CreateFeedResponse feed = feedsExample.createFeed(createFeedSpecification);
        String feedId = feed.getPayload().getFeedId();

        UploadData uploadData = new UploadData();

        //自定义上传编号
        String uploadId = UUID.randomUUID().toString().replace("-", "");

        //设置上传数据信息
        uploadData.setUploadId(uploadId);
        uploadData.setFeedId(feedId);
        uploadData.setSalesman(userName);
        String value = String.valueOf(size);
        uploadData.setCount(value);
        String number = authorization.getNumber();
        uploadData.setAmazonId(number);

        uploadDataService.save(uploadData);

        GetFeedResponse getFeedResponse = feedsExample.getFeed(feedId);
        //第四步
        return getFeedResponse;
    }

    /**
     * 检查产品是否上传成功
     *
     * @param uploadId
     * @return
     * @throws ApiException
     */
    @GetMapping("/check")
    @ApiOperation(value = "检查产品是否上传成功")
    public CommonResult check(String uploadId) throws ApiException {
        //根据上传编号查询上传信息
        UploadData uploadData = uploadDataService.getById(uploadId);
        String feedId = uploadData.getFeedId();
        String amazonId = uploadData.getAmazonId();
        AmazonAuthority amazonAuthority = amazonAuthorityService.getById(amazonId);

        FeedsApi feedsExample = GetFeed.getFeedsExample(amazonAuthority);
        GetFeedResponse feed = feedsExample.getFeed(feedId);
        String statusMessage = "";
        if (feed.getPayload().getProcessingStatus().equals(Feed.ProcessingStatusEnum.DONE)) {
            String resultFeedDocumentId = feed.getPayload().getResultFeedDocumentId();
            if (!StringUtils.isEmpty(resultFeedDocumentId)) {
                GetFeedDocumentResponse feedDocument = feedsExample.getFeedDocument(resultFeedDocumentId);
                String url = feedDocument.getPayload().getUrl();
                String key = feedDocument.getPayload().getEncryptionDetails().getKey();
                String initializationVector = feedDocument.getPayload().getEncryptionDetails().getInitializationVector();

                FeedDocument.CompressionAlgorithmEnum compressionAlgorithm = feedDocument.getPayload().getCompressionAlgorithm();
                DownloadExample downloadExample = new DownloadExample();
                try {
                    if (compressionAlgorithm != null) {
                        downloadExample.downloadAndDecrypt(key, initializationVector, url, compressionAlgorithm.toString());
                    }
                    downloadExample.downloadAndDecrypt(key, initializationVector, url, null);
                    MessageStatus messageStatus = messageStatusService.getById(key);
                    statusMessage = messageStatus.getStatusMessage();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!StringUtils.isEmpty(statusMessage)) {
                    return CommonResult.error(statusMessage);
                } else {
                    return CommonResult.success("ok");
                }
            }
        }
        return CommonResult.success("产品还在队列中");
    }
}

